package com.study.demoservice.controller;

import com.atguigu.annotation.WebLog;
import com.study.demoservice.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.backoff.BackOff;
import org.springframework.util.backoff.BackOffExecution;
import org.springframework.util.backoff.ExponentialBackOff;
import org.springframework.util.backoff.FixedBackOff;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("retry")
@Slf4j
public class RetryController {

    @GetMapping("/one")
    public String retry1() {
        //重试间隔
        long interval = 1000;
        //最大重试次数
        long maxAttempts = 10;
        BackOff backOff = new FixedBackOff(interval, maxAttempts);
        BackOffExecution execution = backOff.start();

        while(true){
            long value = execution.nextBackOff();
            if(value == BackOffExecution.STOP){
                break;
            }else{
                try {

                    TimeUnit.MICROSECONDS.sleep(value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        return "ok";
    }


    @GetMapping("/two")
    public String retry2() {
        int i = 0;
        long initialInterval = 1000;  //初始间隔
        double multiplier = 1.5; //递增倍数
        long maxInterval = 5 * 10000L;  //最大间隔
        long maxElapsedTime = 50 * 1000L;  //累计最大的时间间隔

        ExponentialBackOff backOff = new ExponentialBackOff(initialInterval, multiplier);
        backOff.setMaxInterval(maxInterval);
        backOff.setMaxElapsedTime(maxElapsedTime);

        BackOffExecution execution = backOff.start();

        while(true){
            long value = execution.nextBackOff();
            if(value == BackOffExecution.STOP){
                break;
            }else{
                log.info("=======进来了=======");
                // 在这里写你的重试逻辑
                i = 99;            }
        }

        return String.valueOf(i);
    }

    @Resource
    private PayService payService;

    @GetMapping("retry3")
    @WebLog("减少库存")
    public String retry3(@RequestParam(value = "num", defaultValue = "-1") Integer num) {
        payService.minGoodsNum(num);
        return "ok";
    }


}